package com.hmall.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.utils.RabbitMqHelper;
import com.hmall.common.utils.UserContext;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(value = {RabbitTemplate.class, MessageConverter.class})
public class MqConfig {

    //由于配置类只会在启动类所在包及其子包中被加载,所以要借助spring的自动装配设置
    @Bean
    public MessageConverter messageConverter() {
        Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter() {
            @Override // 在接收到请求后会自动调用
            public Object fromMessage(Message message, Object conversionHint) throws MessageConversionException {
                Long userId = message.getMessageProperties().getHeader("user-info");
                System.out.println("配置类 userId = " + userId);
                if (ObjectUtil.isNotNull(userId)) {//判断不为null
                    UserContext.setUser(userId);
                }
                return super.fromMessage(message, conversionHint);//调用父类方法,将数据转化为java对象
            }
        };
        jackson2JsonMessageConverter.setCreateMessageIds(true);
        return jackson2JsonMessageConverter;
    }

    @Bean
    public RabbitMqHelper rabbitMqHelper(RabbitTemplate rabbitTemplate) {
        return new RabbitMqHelper(rabbitTemplate);
    }
}
